import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';

class ExpandableText extends StatefulWidget {
  final String text;

  final int maxLines;

  final TextStyle style;

  final bool expand;
  final bool isShow;

  const ExpandableText(
      {Key key, this.text, this.maxLines, this.style, this.expand, this.isShow})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ExpandableTextState(text, maxLines, style, expand, isShow);
  }
}

class _ExpandableTextState extends State<ExpandableText> {
  final String text;

  final int maxLines;

  final TextStyle style;

  bool expand;
  bool isShow;

  _ExpandableTextState(
      this.text, this.maxLines, this.style, this.expand, this.isShow) {
    if (expand == null) {
      expand = false;
    }
    if (isShow == null) {
      isShow = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, size) {
      final span = TextSpan(text: widget.text ?? '', style: style);

      final tp = TextPainter(
          text: span, maxLines: maxLines, textDirection: TextDirection.ltr);

      tp.layout(maxWidth: size.maxWidth);

      if (tp.didExceedMaxLines) {
        return Column(
          children: <Widget>[
            expand
                ? Text(widget.text ?? '',
                    textAlign: TextAlign.start, style: style)
                : Text(widget.text ?? '',
                    textAlign: TextAlign.start,
                    maxLines: maxLines,
                    overflow: TextOverflow.ellipsis,
                    style: style),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                setState(() {
                  expand = !expand;
                });
              },
              child: isShow
                  ? Container(
                      alignment: Alignment.centerRight,
                      width: double.infinity,
                      padding: EdgeInsets.only(top: 2),
                      child: Text(expand ? "" : "展开",
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(16),
                              color: Colors.blue)))
                  : Container(
                      height: 0,
                    ),
            ),
          ],
        );
      } else {
        return Container(
            child: Text(widget.text ?? '',
                textAlign: TextAlign.start, style: style),
            alignment: Alignment.topLeft);
      }
    });
  }
}
